package Thread;

/**
 * 单例模式(懒汉模式)
 */
class SingleTonLazy{
    private volatile static SingleTonLazy instance = null; //volatile解决内存可见性和指令重排序问题

    public static SingleTonLazy getInstance() {
        if (instance == null) { //减少上锁的次数优化代码
            synchronized (SingleTonLazy.class) {
                if (instance == null) {  //让实例化对象一次性执行完
                    instance = new SingleTonLazy();
                }
            }
        }
        return instance;
    }

    private SingleTonLazy() {

    }
}

public class ThreadDemo14 {

    public static void main(String[] args) {
        SingleTonLazy s1 = SingleTonLazy.getInstance();
        SingleTonLazy s2 = SingleTonLazy.getInstance();
        System.out.println(s1==s2);
    }

}
